# -*- coding:utf-8 -*-
import csv
import threading

import pymysql
import requests
import json

import time


import os

from click._compat import raw_input

'''
1、处理闲聊增加的语句接口响应
2、尝试使用多线程并发，减少消耗时间


'''
class smallTalkTest():
    '''获取token'''

    def login_token(self):
        # 初始化登录接口
        login_url = 'https://api.icarbonx.com/oauth2/token?grant_type=password&sms_verify=true'
        login_header = {"Authorization": "Basic Y29tLm1ldW0uY29hY2guaXBob25lOjdmYTYyZmFmYzgxZTgwMzY="}
        login_data = {
            "username": "15012345678",
            "password": "888888",
            "appName": "health-buddy",
            "grant_type": "password",
            "sms_verify": "true"
        }
        # 登录请求接口
        r_login = requests.post(url=login_url, data=login_data, headers=login_header)

        # 获取登录的响应报文
        print(r_login.text)
        # login_response = json.loads(r_login.text)
        # 保存登录的token信息
        # access_token = login_response['access_token']
        token = r_login.json()['access_token']
        print(token)
        '''请求接口获取token值'''
        return token


    def smallTalk(self,threadNum):
        # 初始化
        food_flag_init = 0
        qa_error_init = 0
        food_fail_init = 0

        # 开始时间
        start = time.time()

        #判断文件是否存在，存在则删除
        # os.remove('E:\\test\\HB\\small_answer.csv')


        #闲聊的msg
        with open('E:\\test\\HB\\small_talk_init.csv', 'r') as smf:
            reader = csv.reader(smf)
            next(reader)
            for row in reader:
                small_talk_msg = {"msg":row[0]}
                small_talk_headers = {"Authorization": "Bearer " + self.login_token()}

                # 闲聊的url
                small_talk_url = 'https://api.icarbonx.com/chit/st'
                # 闲聊的接口请求
                r_sm = requests.post(url=small_talk_url,data= small_talk_msg,headers= small_talk_headers)
                # 打印闲聊的响应结果
                print(r_sm.text)

                #转换响应结果为dict格式
                r_sm_response = json.loads(r_sm.text)

                # 断言响应结果
                if r_sm_response:
                    print(r_sm_response[0])
                    r_sm_all = r_sm_response[0]
                    r_sm_answer = r_sm_all['answer']

                    r_sm_question = r_sm_all['question']

                else:
                    qa_error_init = qa_error_init + 1
                    print("qa问答失败%d" %qa_error_init)

                data_row = ['question', 'answer']
                if '\n' in r_sm_answer:
                    r_sm_answer = r_sm_answer.replace("\n", ";")

                # 去掉回答结果中的逗号
                # r_sm_answer = r_sm_answer.replace(",", "")

                # 保存chit的answer到本地文件
                with open('E:\\test\\HB\\small_answer.csv', 'a', encoding='utf-8-sig') as f:
                    # csv_write = csv.writer(f)
                    data_row[0] = row[0]
                    data_row[1] = r_sm_answer

                    # data_row = list(data_row)
                    # print(data_row)
                    f.write(','.join(data_row))
                    f.write("\n")
                    # f.write("\\n")

                    f.close()

            # 关闭csv
            smf.close()
            # 计算花费的时间
            print('cost time:{}'.format(time.time() - start))
            print("------qa闲聊模型结果统计" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "------")
            print("qa问答无反馈%d" % qa_error_init)

    def run(self,threadNum,internTime,duration):
        # 创建数组存放线程
        threads = []
        try:
            #创建线程
            for i in range(1,threadNum):
                # 针对函数创建线程
                t = threading.Thread(target=self.smallTalk,args=(i,))
                # 把创建的线程加入线程组
                threads.append(t)
        except Exception as e:
            print(e)

        try:
            # 启动线程
            for thread in threads:
                thread.setDaemon(True)
                thread.start()
                time.sleep(internTime)

            # 等待所有线程结束
            for thread in threads:
                thread.join(duration)
        except Exception as e:
            print(e)









if __name__ == '__main__':
    # fd = smallTalkTest()
    # fd.smallTalk()
    fd = smallTalkTest()
    starttime = time.strftime("%Y-%m-%d %H:%M:%S")

    now = time.strftime("%Y-%m-%d %H:%M:%S")
    duration=raw_input(u"输入持续运行时间：")
    while (starttime+str(duration))!=now:
        fd.run(10,1,int(duration))
        now= time.strftime("%Y-%m-%d %H:%M:%S")




